package com.cskaoyan.mall.search.contoller;

import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.search.consts.PageInfo;
import com.cskaoyan.mall.search.consts.SearchRetCode;
import com.cskaoyan.mall.search.dto.SearchRequest;
import com.cskaoyan.mall.search.dto.SearchResponse;
import com.cskaoyan.mall.search.form.SearchPageInfo;
import com.cskaoyan.mall.search.service.InitDataService;
import com.cskaoyan.mall.search.service.ProductSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @program: csmall-practice
 * @description:
 * @author: Lexis
 * @create: 2022-05-26 19:51
 **/
@Slf4j
@RestController
@RequestMapping("shopping")
public class SearchController {

    @Autowired
    InitDataService initDataService;

    @Autowired
    ProductSearchService productSearchService;


    @GetMapping("search/init")
    public ResponseData initData() {
        initDataService.initItems();
        return new ResponseUtil<>().setData(null);
    }

    @GetMapping("search/{key}")
    public ResponseData getSearchInfo(@PathVariable String key) {
        SearchRequest request = new SearchRequest();
        request.setKeyword(key);
        SearchResponse response = productSearchService.search(request);
        if (response.getCode().equals(SearchRetCode.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(response.getData());
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    @PostMapping("search")
    public ResponseData search(@RequestBody SearchPageInfo pageInfo) {
        SearchRequest request = new SearchRequest();
        request.setKeyword(pageInfo.getKey());
        request.setCurrentPage(pageInfo.getPage());
        request.setPageSize(pageInfo.getSize());
        request.setPriceGt(pageInfo.getPriceGt());
        request.setPriceLte(pageInfo.getPriceLte());
        request.setSort(pageInfo.getSort());

        log.info("request+{}", request);


        SearchResponse response = productSearchService.fuzzySearch(request);
        if (response.getCode().equals(SearchRetCode.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(response);
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }
}
